package br.com.jmed.control;

import java.io.IOException;

import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class SegurancaListener implements PhaseListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void afterPhase(PhaseEvent event) {
		PhaseId id = event.getPhaseId();
		FacesContext context = event.getFacesContext();
		if (id.equals(PhaseId.RESTORE_VIEW)
				&& context.getViewRoot().getViewId().lastIndexOf("login") < 0) {

			if (!context.getExternalContext().getSessionMap()
					.containsKey("usuario")) {
				try {
					context.getExternalContext().redirect(
							context.getExternalContext()
									.getRequestContextPath() + "/login.xhtml");
				} catch (IOException e) {
					throw new FacesException(e);
				}
			}
		}
	}

	public void beforePhase(PhaseEvent event) {

	}

	public PhaseId getPhaseId() {

		return PhaseId.RESTORE_VIEW;
	}

}
